package com.znf.util;

import com.znf.config.CustomUserDetails;
import com.znf.config.AuthProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Data;

import java.util.Date;

@Data
public class JwtUtils {

    private final AuthProperties.JwtProperties jwtProperties;

    public String generatorToken(CustomUserDetails data) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + 1000 * jwtProperties.getExpire());
        return Jwts.builder().header().add("type", "Jwt")
                .and().subject(data.getUsername())
                .claim("userId", data.getUserId())
                .claim("nickName", data.getNickName())
                .issuedAt(now)
                .expiration(expireDate)
                .signWith(Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes()))
                .compact();
    }

    public Claims getClaimsByToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().verifyWith(Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes()))
                .build().parseSignedClaims(token);
        return claimsJws.getPayload();
    }

    public boolean isExpire(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
